import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/services.dart';
import '../message.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert'; // 用于 JSON 编码


class ListMessagePage extends StatefulWidget {
  final String slug;
  const ListMessagePage({
    super.key,
    required this.slug,
  });

  @override
  State<ListMessagePage> createState() => _MyListMessagePageState();
}

class _MyListMessagePageState extends State<ListMessagePage> {
  Map<String, dynamic> favoriteList = {};
  String slug = '';
  
  List<Map<String, Object>> dataList = [];
  String title = '';
  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  final controller = ScrollController();

  Future<void> _logScreenView(slug) async {
    await analytics.logScreenView(
      screenName: '$slug Message Page $slug ES',
      screenClass: '${slug}MessagePage_ES',
    );
  }

  _saveIntList(favoriteList) async {
    final prefs = await SharedPreferences.getInstance();
    // 将数据转换为 JSON 字符串
    String jsonString = jsonEncode(favoriteList);
    
    // 存储 JSON 字符串
    await prefs.setString('message', jsonString);

  }

  Future<Map<String, dynamic>> _getIntList() async {
    final prefs = await SharedPreferences.getInstance();

    // 读取 JSON 字符串
    String? jsonString = prefs.getString('message');
  
    if (jsonString != null) {
      // 将 JSON 字符串转换回 Map
      Map<String, dynamic> jsonData = jsonDecode(jsonString);
      return jsonData;
      // 打印读取的数据
    } else {
      return {};
    }
  }

  @override
  void initState() {
    super.initState();
    slug = widget.slug;

    var listItem = messageDatas.firstWhere((item) => item['slug'] == slug, orElse: () => null);
    if (listItem != null) {
      // print(listItem);
      setState(() {
        dataList = listItem['list'];
        title = listItem['category'];
      });
    } else {
    }
    _logScreenView(slug);
  }

  @override
  Widget build(BuildContext context) {
    double sizewidth = MediaQuery.of(context).size.width;
    
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('images/message_bg.png'), 
          fit: BoxFit.cover
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: PreferredSize(
          preferredSize: const Size.fromHeight(60),
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  offset: const Offset(0, 2),
                  blurRadius: 6.0,
                ),
              ],
            ),
            child: AppBar(
              backgroundColor: Colors.white,
              title: Text(
                title,
                style: const TextStyle(fontFamily: 'OpenSans', color: Colors.black, fontWeight: FontWeight.bold),
              ),
              
            ),
          ),
        ),
        body: SingleChildScrollView(
          controller: controller,
          child:  Padding(
            padding: const EdgeInsets.only(left: 16, right: 16, top: 16),
            child: Column(
              children: [
                for(var index = 0; index < dataList.length; index++)
                  Stack(
                    children: [
                      Container(
                        padding: const EdgeInsets.only(left: 16, right: 64, top: 48, bottom: 48),
                        width: sizewidth - 20,
                        margin: const EdgeInsets.only(bottom: 16),
                        decoration: BoxDecoration(
                          color: const Color.fromRGBO(255, 255, 255, .85),
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.1), // 阴影颜色
                              spreadRadius: 1, // 阴影扩散半径
                              blurRadius: 3, // 模糊半径
                              offset: const Offset(0, 1), // 阴影偏移量
                            ),
                          ],
                        ),
                        child: Text(dataList[index]['text']?.toString() ?? '', style: const TextStyle(fontFamily: 'OpenSans', color: Colors.black, fontSize: 16),),
                        
                      ),
                      Positioned(
                        left: 0, 
                        top: 0, 
                        child: Container(
                          width: 30,
                          height: 20,
                          decoration: const BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.only(topLeft: Radius.circular(8), bottomRight: Radius.circular(8))
                          ),
                          child: Center(
                            child: Text('${index+1}', style: const TextStyle(fontFamily: 'OpenSans', color: Colors.white, fontSize: 14),),
                          ),
                        ) ,
                      ),
                      
                      Positioned(
                        right: 8,
                        top: 12,
                        child: InkWell(
                          onTap: () {
                            Clipboard.setData(
                            ClipboardData(
                              text: dataList[index]['text']?.toString() ?? '',
                            ),
                          ).then((_) {
                            ScaffoldMessenger.of(context)
                                .showSnackBar(
                              const SnackBar(
                                backgroundColor: Colors.green,
                                content: Text(
                                  'Successfully copied to clipboard!',
                                  style: TextStyle(
                                      fontFamily: 'Ubuntu',
                                      fontSize: 16),
                                ),
                              ),
                            );
                          });
                          },
                          child: Container(
                            width: 32,
                            height: 32,
                            decoration: BoxDecoration(
                              // borderRadius: BorderRadius.circular(18),
                              gradient: const LinearGradient(
                                colors: [Colors.green, Colors.blue],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                              borderRadius: BorderRadius.circular(15),
                            ),
                            child: const Icon(Icons.copy, color: Colors.white,size: 18,),
                          ),
                        )
                      ),
                      Positioned(
                        right: 8,
                        top: 54,
                        child: InkWell(
                          onTap: () async {
                            Map<String, dynamic> favoriteList = await _getIntList();
                            
                            setState(() {
                              String itemId = dataList[index]['id'].toString();
                              if (favoriteList[slug] != null && favoriteList[slug].contains(itemId)) {
                                favoriteList[slug].remove(itemId);
                                dataList[index]['like'] = 0;
                              } else {
                                // 检查 slug 是否存在，如果不存在则初始化为一个空列表
                                if (favoriteList[slug] == null) {
                                  favoriteList[slug] = [];
                                }

                                favoriteList[slug].add(itemId);
                                
                                dataList[index]['like'] = 1;
                              }
                            });
                            print(favoriteList);
                            _saveIntList(favoriteList);
                          },
                          child: Container(
                            width: 32,
                            height: 32,
                            decoration: BoxDecoration(
                              // borderRadius: BorderRadius.circular(18),
                              gradient: const LinearGradient(
                                colors: [Colors.blue, Colors.purple],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                              borderRadius: BorderRadius.circular(15),
                            ),
                            child: Icon(Icons.favorite, color: dataList[index]['like'] == 1 ? const Color.fromARGB(255, 255, 251, 0) : Colors.white,size: 18,),
                          ),
                        )
                      )
                    ],
                  )
                  
              ],
            ),
          ),
        ) 
      ),
    ) ;
  }
}


